package com.drore.cloud.controller;

import com.drore.cloud.constant.LocalConstant;
import com.drore.cloud.jdbc.MultiDS;
import com.drore.cloud.sdkjdbc.core.JdbcRunner;
import com.drore.cloud.sdkjdbc.model.Pagination;
import com.drore.cloud.sdkjdbc.model.QueryParam;
import com.drore.cloud.sdkjdbc.model.RestMessage;
import com.drore.cloud.utils.GsonUtil;
import com.drore.cloud.utils.MapClearUtil;
import com.drore.cloud.utils.ThreadLocalHolder;
import com.google.gson.Gson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Objects;

/***
 * 说明
 * 项目名称
 * @since:cloud-ims 1.0
 * @author <a href="mailto:baoec@drore.com">baoec@drore.com </a> 
 * 2017/09/19 13:48
 */
@Api("数据库具体数据模块")
@RestController
public class DataCtl {

    @Autowired
    private MultiDS mult;

    @RequestMapping(value = "/data/table/save" ,method = {RequestMethod.POST, RequestMethod.GET})
    public RestMessage save(String resource_name, String submit_data) {
        Map<String, Object> sys_user_info = (Map<String, Object>) ThreadLocalHolder.getCurrentUser();
        JdbcRunner jdbc = mult.getSessionRunner(Objects.toString(sys_user_info.get("data_source_id")));
        RestMessage rm=new RestMessage();
        Gson gson = GsonUtil.create();
        Map<String, Object> map = (Map<String,Object>)gson.fromJson(submit_data, Map.class);
        if(map.get("file")!=null){
            map.remove("file");
        }
        String insert=null;
        map= MapClearUtil.clear(map);
        if(map.get("id")==null){
             insert=jdbc.insert(resource_name,map);
        }else {
             insert=jdbc.update(resource_name,map);
        }
        rm.setData(insert);
        return rm;
    }



    @ApiOperation("通用列表接口(已经支持复杂查询)")
    @PostMapping("/data/table/list")
    public Pagination<Map> list(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10")Integer limit, String querydata, String resource_name ) {

        Map<String, Object> sys_user_info = (Map<String, Object>) ThreadLocalHolder.getCurrentUser();
        JdbcRunner jdbc = mult.getSessionRunner(Objects.toString(sys_user_info.get("data_source_id")));
        System.out.println("前端查询对象json:"+querydata);

        QueryParam query=new QueryParam(page,limit);
        query.addSort("create_time","desc");

        QueryParam.Param param = GsonUtil.create().fromJson(querydata, QueryParam.Param.class);
        if(param!=null){
            query.setParam(param);
        }
        Pagination    pagination = jdbc.queryListByExample(resource_name, query);
        return pagination;
    }


}
